package com.example.forum.service.impl;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.exception.ApplicationException;
import com.example.forum.service.IPictureService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 功能描述:
 *
 * @author Lenovo
 * @date 2025/1/1
 */
@Service
public class PictureServiceImpl implements IPictureService {
    @Value("${pic.local-path}")
    private String localPath;

    @Override
    public String savePicture(MultipartFile multipartFile) {
        //创建目录
        File dir = new File(localPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        //创建索引
        String fileName = multipartFile.getOriginalFilename();
        assert fileName != null;
        String suffix = fileName.substring(fileName.lastIndexOf("."));//获取文件后缀
        fileName = UUID.randomUUID() + suffix;
        //保存图片
        try {
            multipartFile.transferTo(new File(localPath + "/" + fileName));
        } catch (IOException e) {
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }
        return fileName;
    }
}
